<template>
  <div>
    <a-page-header
      style="border: 1px solid rgb(235, 237, 240)"
      :title="$route.query.id > 0 ? '编辑活动' : '新建活动'"
      :ghost="false"
      @back="() => $router.go(-1)"
    ></a-page-header>

    <page-header-wrapper>
      <a-card :bordered="false">
        <a-form-model ref="form" :model="form" :rules="formRules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
          <h3 class="title">活动设置</h3>
          <a-form-model-item label="活动名称" prop="name">
            <a-input v-model="form.name" placeholder="请输入活动名称" class="maxWidth" />
          </a-form-model-item>

          <a-form-model-item label="活动日期" prop="queryTime">
            <a-range-picker
              show-time
              class="maxWidth"
              format="YYYY-MM-DD HH:mm:ss"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              :placeholder="['开始时间', '结束时间']"
              v-model="form.queryTime"
            />
          </a-form-model-item>

          <a-divider />
          <h3 class="title">规则设置</h3>
          <a-form-model-item style="padding-bottom: 10px" label="成团人数" prop="party_size">
            <div class="flex maxWidth" style="padding-bottom: 10px">
              <a-input-number style="flex: 1" v-model="form.party_size" :min="0" :precision="0" />
            </div>
          </a-form-model-item>
          <a-form-model-item style="padding-bottom: 10px" label="拼团成功人数" prop="party_size">
            <div class="flex maxWidth" style="padding-bottom: 10px">
              <a-input-number style="flex: 1" v-model="form.party_winner_size" :min="0" :precision="0" />
            </div>
            <text
              >为0，默认参与拼团所有人皆可拼团成功。如成团5人，拼团成功人数1人，则成团5人后，随机抽取一人拼团成功，其余人拼团失败。</text
            >
          </a-form-model-item>
          <a-form-model-item
            style="padding-bottom: 10px"
            label="单日拼团次数"
            prop="join_num"
            help="单日每人单商品拼团次数,0代表不限制"
          >
            <div class="flex maxWidth" style="padding-bottom: 10px">
              <a-input-number style="flex: 1" v-model="form.join_num" :min="0" :precision="0" />
            </div>
          </a-form-model-item>

          <a-form-model-item
            style="padding-bottom: 10px"
            label="拼团结束时间（小时）"
            prop="join_num"
            help="当拼团人数不足时，倒计时结束拼团时间"
          >
            <div class="flex maxWidth" style="padding-bottom: 10px">
              <a-input-number style="flex: 1" v-model="form.split_time" :min="0" :precision="0" />
            </div>
          </a-form-model-item>

          <a-form-model-item
            style="padding-bottom: 10px"
            label="开团需消耗积分数量"
            prop="head_integral"
            help="设置后团长团，必须有积分才能开团，团长没有积分不能开团"
          >
            <div class="flex maxWidth" style="padding-bottom: 10px">
              <a-input-number style="flex: 1" v-model="form.head_integral" :min="0" :precision="0" />
            </div>
          </a-form-model-item>

          <a-form-model-item style="padding-bottom: 10px" label="团长免单" prop="head_is_free">
            <a-radio-group v-model="form.head_is_free">
              <a-radio :value="1">开启</a-radio>
              <a-radio :value="0">关闭</a-radio>
            </a-radio-group>
          </a-form-model-item>

          <a-divider />
          <h3 class="title">活动商品</h3>

          <a-button style="margin-bottom: 10px" type="primary" @click="openGoods"> 添加商品 </a-button>

          <a-table :data-source="form.goods" :columns="columns" :pagination="false">
            <div slot="content" slot-scope="scope, text">
              <div class="imgTxt">
                <div class="img">
                  <img :src="text.cover_pic" alt="" />
                </div>
                <div class="txt">
                  <div class="name">{{ text.name }}</div>
                </div>
              </div>
            </div>

            <!-- 虚拟活动销量 -->
            <div slot="virtual_sales" slot-scope="scope, text">
              <a-input-number size="small" v-model="text.virtual_sales" :min="0" :precision="0" />
            </div>

            <!-- 活动价格 -->
            <div slot="seckillPrice" slot-scope="scope, text">
              <template v-if="text.use_attr === '1'">
                <span class="btnAttr" @click="setAttr(text)">设置活动价格</span>
              </template>
              <a-input-number size="small" v-else v-model="text.pt_price" :min="0" :precision="2" />
            </div>

            <!-- 活动分类 -->
            <div slot="cat_id" slot-scope="scope">
              <a-select v-model="scope.cat_id" size="small">
                <a-select-option v-for="cat in catList" :key="cat.id"> {{ cat.name }} </a-select-option>
              </a-select>
            </div>

            <div slot="actions" slot-scope="scope, text">
              <a-button type="link" @click="remove(text)" size="small">删除</a-button>
            </div>
          </a-table>

          <div class="btnBox">
            <a-button v-loading="btnLoading" :disabled="disabled" type="primary" @click="onSubmit"> 提交 </a-button>
            <a-button style="margin-left: 10px" @click="$router.go(-1)"> 取消 </a-button>
          </div>
        </a-form-model>
      </a-card>

      <popGoods @onOk="selectGoods" :checkList="form.goods" ref="popGoods"></popGoods>
      <popAttr @onOk="setAttrPop" ref="popAttr" :item="item"></popAttr>
    </page-header-wrapper>
  </div>
</template>

<script>
import pt from '@/api/pt'
import popGoods from './components/goods.vue'
import popAttr from './components/attr.vue'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 120,
  },
  {
    title: '商品名称',
    dataIndex: 'content',
    width: 250,
    scopedSlots: { customRender: 'content' },
  },
  {
    title: '售价',
    dataIndex: 'price',
    key: 'price',
    ellipsis: true,
    sorter: (a, b) => a.price - b.price,
  },
  {
    title: '总库存',
    dataIndex: 'goods_num',
    key: 'goods_num',
    ellipsis: true,
    sorter: (a, b) => a.goods_num - b.goods_num,
  },
  {
    title: '虚拟活动销量',
    dataIndex: 'virtual_sales',
    scopedSlots: { customRender: 'virtual_sales' },
    sorter: (a, b) => a.virtual_sales - b.virtual_sales,
  },
  {
    title: '活动价格',
    dataIndex: 'seckillPrice',
    scopedSlots: { customRender: 'seckillPrice' },
  },
  {
    title: '活动分类',
    scopedSlots: { customRender: 'cat_id' },
    width: 200,
  },
  {
    title: '操作',
    dataIndex: 'actions',
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  components: {
    popGoods,
    popAttr,
  },

  data() {
    return {
      btnLoading: false,
      disabled: false,

      item: null,

      columns,

      form: {
        id: '',
        name: '',
        queryTime: [],
        party_size: '0',
        party_winner_size: '0',
        join_num: '0',
        is_use_coupon: '1',
        goods: [],
        head_is_free: 0,
        head_integral: 0,
      },

      // 支付宝验证规则
      formRules: {
        name: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        queryTime: [
          {
            required: true,
            message: '请选择活动时间',
            trigger: 'change',
          },
        ],
        party_size: [{ required: true, message: '请选择拼团人数', trigger: 'blur' }],
        join_num: [{ required: true, message: '请选择每日拼中次数', trigger: 'blur' }],
        head_is_free: [{ required: true, message: '请选择', trigger: 'change' }],
        head_integral: [{ required: true, message: '请填写', trigger: 'blur' }],
      },

      catList: [],
    }
  },
  created() {
    this.getCatList()
  },

  methods: {
    async getCatList() {
      const res = await pt.catGetListNopage()
      this.catList = res.data.data
    },
    openGoods() {
      // this.$nextTick(() => {
      console.log('11111,', this.$refs)
      this.$refs.popGoods.visible = true
      // })
    },

    selectGoods(list) {
      var newList = []
      list.forEach((item) => {
        let newItem = item
        let findItem = this.form.goods.find((goods) => goods.id == item.id)
        if (findItem) {
          newItem = findItem
        }
        newList.push(newItem)
      })
      this.form.goods = newList
    },

    remove(item) {
      let { goods } = this.form,
        index = goods.findIndex((el) => el.id === item.id)

      goods.splice(index, 1)
    },

    setAttr(item) {
      this.item = item
      this.$refs.popAttr.visible = true
    },

    setAttrPop(item) {
      let { goods } = this.form,
        index = goods.findIndex((el) => el.id === item.id)

      this.$set(goods[index], 'attr', item.attr)
    },

    // 点击提交
    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))

          if (!form.goods.length) return this.$message.error('请选择活动商品~')

          if (parseInt(form.party_size) < parseInt(form.party_winner_size))
            return this.$message.error('拼团成功人数不能大于成团人数~')
          // form.goods = form.goods.map((el) => {
          //   if (el.attr) {
          //     el.attr = el.attr
          //       .filter((e) => e.checked)
          //       .map((e) => {
          //         delete e.checked
          //         return e
          //       })
          //   }
          //   return el
          // })

          form.start_time = form.queryTime[0]
          form.end_time = form.queryTime[1]
          delete form.queryTime

          console.log('submitForm', form)

          this.btnLoading = true
          const res = await pt.activitySave(form)

          this.btnLoading = false

          if (!res.code) {
            this.$message.success(res.msg)
            this.$router.back()
            return
          }

          this.$message.error(res.msg)
        } else {
          return false
        }
      })
    },
  },

  async mounted() {
    let id = this.$route.query.id

    if (!id) return
    const hide = this.$message.loading('请稍等', 0)

    let res = await pt.activityGetInfo({
      id,
    })
    hide()
    if (res.code) return this.$message.error(res.msg)
    let { start_time, end_time } = res.data.activity
    let { activity_goods: goods } = res.data

    // goods = goods.map((el) => {
    //   if (el.attr) {
    //     el.attr.forEach((e) => {
    //       e.checked = true
    //     })
    //   }
    //   return el
    // })

    this.form = { ...res.data.activity, goods, queryTime: [start_time, end_time] }
  },
}
</script>

<style lang="less" scoped>
.title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 14px;
  font-weight: bold;
}

.flex {
  display: flex;

  .slot {
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    height: 32px;
    width: 32px;
    background: rgba(247, 247, 247, 1);
    text-align: center;
  }
}

.maxWidth {
  width: 480px;
}

.imgTxt {
  display: flex;

  .img {
    width: 50px;
    height: 50px;

    img {
      display: block;
      width: 100%;
      height: 100%;
    }
  }

  .txt {
    flex: 1;
    overflow: hidden;
    margin-left: 10px;
  }

  .name {
    display: -webkit-box;
    white-space: normal;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
    overflow: hidden;
  }
}

.btnAttr {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  font-size: 12px;
  width: 90px;
  height: 24px;
  border: 1px solid #d9d9d9;
  box-sizing: border-box;
  cursor: pointer;
}

.btnBox {
  padding-top: 20px;
  text-align: center;
}
</style>
